//
//  BeaconViewController.m
//  ios7Sample
//
//  Created by GeIL on 16/7/14.
//  Copyright © 2016年 KS. All rights reserved.
//

#import "BeaconViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import <CoreLocation/CoreLocation.h>
#import "PulsingHaloLayer.h"
#define kProximityUUID @"C41EDB73-E42B-41B3-9289-620F9ADC29C3"
#define KIdentifier @"com.shu223.ios7sampler"

@interface BeaconViewController ()<CLLocationManagerDelegate, CBPeripheralManagerDelegate>

//For center


@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLBeaconRegion *beaconRegion;

@property (nonatomic,weak) IBOutlet UILabel *statusLabel;
@property (nonatomic,weak) IBOutlet UILabel *proximitylablel;
@property (nonatomic,weak) IBOutlet UILabel *rssLablel;
@property (nonatomic,weak) IBOutlet UILabel *accurarylabel;


//for peripherarl

@property (nonatomic ,strong) CBPeripheralManager *periphearlManger;

@property (nonatomic,weak) IBOutlet UIView *overlayView;
@property (nonatomic ,weak) IBOutlet UILabel *stateLable;

@end

@implementation BeaconViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.overlayView.hidden =YES;
    
    [self resetlabels];
    [self startRegionMonitoring];

}


#pragma mark -for central

- (void)resetlabels{
    self.statusLabel.text = @"No beacon";
    self.proximitylablel.text = nil;
    self.accurarylabel.text = nil;
    
    
}

- (void)startRegionMonitoring{
    if ([CLLocationManager isMonitoringAvailableForClass:[CLBeaconRegion class]]) {
        self.locationManager =[[CLLocationManager alloc]init];
        self.locationManager.delegate =self;
        NSUUID *uuid =[[NSUUID alloc]initWithUUIDString:kProximityUUID];
        self.beaconRegion =[[CLBeaconRegion alloc]initWithProximityUUID:uuid identifier:KIdentifier];
        [self.locationManager startMonitoringForRegion:self.beaconRegion];
    }
}

- (void)startRanggingInRegion:(CLRegion *)region{
    if ([region isMemberOfClass:[CLBeaconRegion class]] && [CLLocationManager isRangingAvailable]) {
        self.statusLabel.text =@"Beacon in Range";
        [self.locationManager startMonitoringForRegion:self.beaconRegion];
    }
}


#pragma mark --CLLocationMangerDelegate

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    NSLog(@"status==:%d",status);
    
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                [self.locationManager requestAlwaysAuthorization];
            }
            break;
            case kCLAuthorizationStatusAuthorizedWhenInUse:
            case kCLAuthorizationStatusAuthorizedAlways:
            
        default:
            break;
    }
}

- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(nonnull CLRegion *)region
{
    NSLog(@"start monioring for region");
    [self.locationManager requestStateForRegion:self.beaconRegion];
}


- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(nullable CLRegion *)region withError:(nonnull NSError *)error
{
    NSLog(@"fail monitoring with error %@",error);
}


-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didfailwithError %@",error);
}


- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(nonnull CLRegion *)region
{
    switch (state) {
        case CLRegionStateInside:
        {
            [self startRanggingInRegion:region];
            break;
        }
        case CLRegionStateOutside:
        case  CLRegionStateUnknown:
            
        default:
            break;
    }
}


- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
{
    [self resetlabels];
    if ([region isMemberOfClass:[CLBeaconRegion class]] && [CLLocationManager isRangingAvailable]) {
        [self.locationManager stopRangingBeaconsInRegion:(CLBeaconRegion *)region];
    }
}


- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(nonnull NSArray<CLBeacon *> *)beacons inRegion:(nonnull CLBeaconRegion *)region
{
    CLBeacon  *beacon = beacons.firstObject;
    NSString *proximityStr;
    switch (beacon.proximity) {
        case CLProximityImmediate:
        {
            proximityStr  = @"Immediate";
            break;
        }
        case CLProximityNear:
        {
            proximityStr =@"Near";
            break;
        }
    
        case CLProximityFar:
        {
            proximityStr =@"Far";
        }
            
        
        default:
        {
            proximityStr = @"Unkonwn";
            break;
        }
            
    }
    self.proximitylablel.text = proximityStr;
    self.rssLablel.text =[NSString stringWithFormat:@"%ld [db]",(long)beacon.rssi];
    self.accurarylabel.text = [NSString stringWithFormat:@"%.0f[m]", beacon.accuracy];
    
}


#pragma makr - for peripheral


- (void)startAdverrting{
    NSUUID *uuid =[[NSUUID alloc]initWithUUIDString:kProximityUUID];
    CLBeaconRegion *beaconRegion=[[CLBeaconRegion alloc]initWithProximityUUID:uuid identifier:KIdentifier];
    NSDictionary *beaconPeripheralData=[beaconRegion peripheralDataWithMeasuredPower:nil];
    [self.periphearlManger startAdvertising:beaconPeripheralData];
}
- (IBAction)pressTrunIntoBeaacon {
    self.locationManager.delegate = nil;
    [self.locationManager stopMonitoringForRegion:self.beaconRegion];
    [self resetlabels];
    self.stateLable.text = nil;
    self.overlayView.hidden = NO;
    self.periphearlManger = [[CBPeripheralManager alloc]initWithDelegate:self queue:nil options:nil];
    if (self.periphearlManger.state == CBPeripheralManagerStatePoweredOn) {
        [self startAdverrting];
    }
    
}

#pragma mark -CBPeripheralManagerDelegate

- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error
{
    if (error) {
        NSLog(@"faild to  start adverting with  error %@",error);
    }
    else{
        NSLog(@"start Adevertintsing");
        //show beacon's pulsh
        
      PulsingHaloLayer *layer = [PulsingHaloLayer layer];
        layer.position = self.overlayView.center;
        layer.radius = 160.;
        [self.overlayView.layer insertSublayer:layer atIndex:0];
        
    }
}

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
{
    NSString *stateStr;
    switch (peripheral.state) {
        case CBPeripheralManagerStatePoweredOn:
        {
            stateStr =@"PowerOn";
            
            [self startAdverrting];
            
            break;
        }
        default:
            
            stateStr = nil;
            break;
    }
    self.stateLable.text = [NSString stringWithFormat:@"%@",stateStr];
}


@end
